//
//  ZMYHadPayFavoritesTableViewController.m
//  奇阅
//
//  Created by 奇阅科技 on 14-10-31.
//  Copyright (c) 2014年 奇阅科技. All rights reserved.
//

#import "ZMYHadPayFavoritesTableViewController.h"
#import "ZMYHadPayFavoritesTableViewCell.h"
#import "Config.h"
#import "ZMYBookInfoViewController.h"
#import "UIScrollView+VORefresh.h"
@interface ZMYHadPayFavoritesTableViewController ()<FavoritesTableViewCellDelegate>
{
    NSMutableArray *dataArray;
    ///是否还有下一页
    BOOL isHasMore;
}
@end

@implementation ZMYHadPayFavoritesTableViewController
-(void)dealloc{
    NSLog(@"HadPayFavorites释放了");
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setBarBackgroundImage:@"navBackground"];
    self.navigationController.navigationBarHidden = NO;
    
    if (self.isHadPay) {
        [self setTitleForNavigation:@"已购"];
        self.defaultImageView.image = [UIImage imageNamed:@"HadPay"];
    } else {
        [self setTitleForNavigation:@"收藏"];
        self.defaultImageView.image = [UIImage imageNamed:@"HadFavorites"];
    }
    [self setLeftBackButtonForNavigation];
    
    [self.tableView addTopRefreshWithTarget:self action:@selector(getNetNewDataArray)];
    if (self.isHadPay) {
        [self.tableView addBottomRefreshWithTarget:self action:@selector(getMoreDataArray)];
    }
    [self initDataArray];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
//    self.extendedLayoutIncludesOpaqueBars = YES;
}
-(void)initDataArray{
    if (self.isHadPay) {
        dataArray = [NSMutableArray arrayWithArray:[[ZMYLKDB getLKDBHelper] getMyVIPBookPage:1]];
        [self.tableView reloadData];
    } else {
        dataArray = [NSMutableArray arrayWithArray:[[ZMYLKDB getLKDBHelper] getMyFavorBook]];
        [self.tableView reloadData];
    }
    [self getNetNewDataArray];
}
-(void)getNetNewDataArray{
    if (self.isHadPay) {
        [self.navigationController setSGProgressPercentage:80 andTintColor:YellowColor];
        [[ZMYNetWorkAPI default]myVIPPage:1 Response:^(NSDictionary *resultDic) {
            [self.navigationController setSGProgressPercentage:100];
            NSArray *booklist = [resultDic objectForKey:@"booklist"];
            if (booklist.count>0) {
                dataArray = [NSMutableArray arrayWithArray:[[ZMYLKDB getLKDBHelper] getMyVIPBookPage:1]];
                [self.tableView reloadData];
            }
            NSInteger count = [[resultDic objectForKey:@"count"] integerValue];
            if (dataArray.count<count) {
                isHasMore = YES;
            }else{
                isHasMore = NO;
                [self.tableView removeBottomRefresh];
            }
            [self.tableView.topRefresh endRefreshing];
        } error:^(NSString *errorStr) {
            [self.tableView.topRefresh endRefreshing];
            [self.navigationController cancelSGProgress];
        }];
    } else {
        [self.navigationController setSGProgressPercentage:80 andTintColor:YellowColor];
        [[ZMYNetWorkAPI default]myFavorResultArray:^(NSArray *resultArray) {
            [self.navigationController setSGProgressPercentage:100];
            dataArray = [NSMutableArray arrayWithArray:[[ZMYLKDB getLKDBHelper] getMyFavorBook]];
            [self.tableView reloadData];
            [self.tableView.topRefresh endRefreshing];
        } error:^(NSString *errorStr) {
            [self.navigationController cancelSGProgress];
        }];
    }
}
-(void)getMoreDataArray{
    if (isHasMore) {
        if (self.isHadPay) {
            [[ZMYNetWorkAPI default]myVIPPage:dataArray.count/10+1 Response:^(NSDictionary *resultDic) {
                [self.tableView.bottomRefresh endRefreshing];
                NSArray *booklist = [resultDic objectForKey:@"booklist"];
                if (booklist.count>0) {
                    [dataArray addObjectsFromArray:[[ZMYLKDB getLKDBHelper] getMyVIPBookPage:dataArray.count/10+1]];
                    [self.tableView reloadData];
                }
                NSInteger count = [[resultDic objectForKey:@"count"] integerValue];
                if (dataArray.count<count) {
                    isHasMore = YES;
                }else{
                    isHasMore = NO;
                    [self.tableView removeBottomRefresh];
                }
            } error:^(NSString *errorStr) {
                [self.tableView.bottomRefresh endRefreshing];
                [AppDelegate showHUDAndHide:errorStr view:self.view];
            }];
        }
//        else {
//            [self.navigationController setSGProgressPercentage:80 andTintColor:YellowColor];
//            [[ZMYNetWorkAPI default]myFavorResultArray:^(NSArray *resultArray) {
//                [self.navigationController setSGProgressPercentage:100];
//                dataArray = [NSMutableArray arrayWithArray:[[ZMYLKDB getLKDBHelper] getMyFavorBook]];
//                [self.tableView reloadData];
//            } error:^(NSString *errorStr) {
//                [self.navigationController cancelSGProgress];
//            }];
//        }
    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if (dataArray.count<1) {
        self.defaultImageView.hidden = NO;
    } else {
        self.defaultImageView.hidden = YES;
    }
    return dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZMYHadPayFavoritesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZMYHadPayFavoritesTableViewCell" forIndexPath:indexPath];
    
    if (self.isHadPay) {
        MyVIPBook *book = dataArray[indexPath.row];
        [cell.coverImageView setImageWithURL:[NSURL URLWithString:book.book.imagefname]placeholderImage:[UIImage imageNamed:@"defaultCover"]];
        cell.bookTitleLabel.text = book.book.title;
        cell.authorLabel.text = [NSString stringWithFormat:@"作       者:%@",book.book.author];
        if (book.finishflag) {
            cell.lastUpdateInfoLabel.text = [NSString stringWithFormat:@"已完本"];
        } else {
            cell.lastUpdateInfoLabel.text = [NSString stringWithFormat:@"最新章节:%@",book.lastUpdateInfo];
        }
        cell.cancelFavoritesButton.hidden = YES;
    } else {
        MyFavorBook *book = dataArray[indexPath.row];
        [cell.coverImageView setImageWithURL:[NSURL URLWithString:book.book.imagefname]placeholderImage:[UIImage imageNamed:@"defaultCover"]];
        cell.bookTitleLabel.text = book.book.title;
        cell.authorLabel.text = [NSString stringWithFormat:@"作       者:%@",book.book.author];
        if (book.finishflag) {
            cell.lastUpdateInfoLabel.text = [NSString stringWithFormat:@"已完本"];
        } else {
            cell.lastUpdateInfoLabel.text = [NSString stringWithFormat:@"最新章节:%@",book.lastUpdateInfo];
        }
        cell.cancelFavoritesButton.hidden = NO;
        cell.delegate = self;
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ZMYBookInfoViewController *view = [self.storyboard instantiateViewControllerWithIdentifier:@"ZMYBookInfoViewController"];
    if ([dataArray[indexPath.row] isKindOfClass:[MyVIPBook class]]) {
        view.book =((MyVIPBook *)dataArray[indexPath.row]).book;
    } else {
        view.book =((MyFavorBook *)dataArray[indexPath.row]).book;
    }
    [self.navigationController pushViewController:view animated:YES];
}
-(void)cancelFavorites:(ZMYHadPayFavoritesTableViewCell *)cell{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if ([dataArray[indexPath.row] isKindOfClass:[MyFavorBook class]]) {
        MyFavorBook *book = dataArray[indexPath.row];
        [dataArray removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        [[ZMYLKDB getLKDBHelper] deleteMyFavorBook:book];
        [UIView animateWithDuration:1 delay:1 options:UIViewAnimationOptionLayoutSubviews animations:^{
//            [self.tableView reloadData];
        } completion:^(BOOL finished) {
            
        }];
        
        [[ZMYNetWorkAPI default] removeMyFavorArticleid:book.articleid response:^(NSDictionary *resultDic) {
            
        } error:^(NSString *errorStr) {
            
        }];
    }
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
